﻿using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using Silent.WCF.Base.Common;
using Silent.WCF.Interfaces;

namespace Silent.WCF.Base
{
    public abstract class ClientServiceBuilderBase<TService> where TService : class, IService
    {
        private ClientService<TService> m_clientService;

        public IClientService<TService> Build(string host, int port)
        {
            m_clientService = new ClientService<TService>(GetBinding(), GetEndpoint(host, port));
            AddEndpointBehaviors();
            return m_clientService;
        }

        protected abstract void AddEndpointBehaviors();
        protected void AddEndpointBehavior<T>(T endpointBeavior) where T : class, IEndpointBehavior
        {
            m_clientService.Endpoint.Behaviors.Add(endpointBeavior);
        }
        protected virtual Binding GetBinding()
        {
            return BindingFactory.DefaultTcpBinding;
        }
        protected virtual EndpointAddress GetEndpoint(string host, int port)
        {
            var uri = new UriBuilder().GetAddress(host, port, typeof(TService).ToString());
            return new EndpointAddress(uri);
        }

        public class ClientService<T> : ClientBase<T>, IClientService<T> where T : class, IService
        {
            public T Service
            {
                get { return Channel; }
            }

            public ClientService(Binding binding, EndpointAddress remoteAddress)
                : base(binding, remoteAddress)
            {

            }
        }
    }
}